{% extends "layout/project.html" %}
{% load static %}

{% block css1 %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<!-- 在页面头部引入 SweetAlert2 -->
<link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
<style>
    /* 自定义样式 */
    .swal2-title {
        font-size: 1.4rem !important;
    }

    .swal2-html-container {
        text-align: left !important;
        margin: 1rem 0 !important;
    }

    .swal2-confirm {
        background: #1890ff !important;
        border-radius: 4px !important;
    }
</style>

<style>
    .file-manager {
        height: calc(100vh - 72px);
        background-color: #f8f9fa;
    }

    .directory-pane {
        width: 280px;
        border-right: 1px solid #dee2e6;
        background: white;
    }

    .file-item:hover {
        background-color: rgba(0, 0, 0, 0.03);
    }

    .file-icon {
        width: 36px;
        text-align: center;
    }

    .breadcrumb-divider {
        --bs-breadcrumb-divider: '>';
    }

    /* CSS */
    .upload-file {
        opacity: 0;
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        /* 覆盖整个按钮区域 */
        height: 100%;
        cursor: pointer;
        /* 显示手型光标 */
    }

    /* 移除默认边框（Firefox 兼容性处理） */
    .upload-file::-webkit-file-upload-button {
        display: none;
    }

    .upload-progress {
        position: fixed;
        right: 2px;
        bottom: 2px;
        width: 400px;
    }

    .upload-progress .progress-error {
        color: red;
    }
</style>
{% endblock  %}
{% block content1 %}

<!-- 导航栏 -->
<nav class="navbar navbar-expand-lg bg-white shadow-sm">
    <div class="container-fluid">
        <a class="navbar-brand" href="{% url 'file' project_id=request.tracer.project.id %}">
            <i class="fa-solid fa-cloud me-2 text-primary"></i>云端文件存储库
        </a>

        <!-- 搜索框 -->
        <div class="d-flex flex-grow-1 mx-4">
            <form class="w-100">
                <div class="input-group">
                    <input type="search" class="form-control" placeholder="搜索文件或文件夹...">
                    <button class="btn btn-outline-secondary" type="button">
                        <i class="fa-solid fa-magnifying-glass"></i>
                    </button>
                </div>
            </form>
        </div>

        <!-- 操作按钮 -->
        <div class="d-flex gap-2">
            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addModal"
                data-whatever="新建文件夹">
                <i class="fa-solid fa-folder-plus me-2"></i>新建
            </button>
            <!-- HTML -->
            <button class="btn btn-success btn-sm position-relative overflow-hidden">
                <i class="fa-solid fa-upload me-2"></i>上传
                <input type="file" class="upload-file" multiple name="uploadFile" id="uploadFile" title=" ">
            </button>
        </div>
    </div>
</nav>

<!-- 主容器 -->
<!-- 面包屑导航部分 -->
<ol class="breadcrumb breadcrumb-divider mb-0 py-2 px-4">
    <li class="breadcrumb-item">
        <a href="{% url 'file' project_id=request.tracer.project.id %}" class="text-decoration-none">
            <i class="fa-solid fa-house"></i> 文件首页
        </a>
    </li>
    {% for record in breadcrumb_list %}
    <li class="breadcrumb-item">
        <a href="{% url 'file' project_id=request.tracer.project.id %}?folder_id={{ record.id }}"
            class="text-decoration-none">{{ record.name }}</a>
    </li>
    {% endfor %}
</ol>

<!-- 文件列表部分 -->
<div class="p-3" style="height: calc(100vh - 180px); overflow-y: auto;">
    <div class="list-group">
        {% for item in file_object_list %}
        <div class="list-group-item file-item d-flex align-items-center mb-3">
            <!-- 文件图标 -->
            <div class="file-icon me-3">
                {% if item.file_type == 2 %}
                <i class="fa-solid fa-folder text-warning"></i>
                {% else %}
                {% if item.name|lower|slice:'-4:' == '.pdf' %}
                <i class="fa-solid fa-file-pdf text-danger"></i>
                {% elif item.name|lower|slice:'-5:' == '.docx' %}
                <i class="fa-solid fa-file-word text-primary"></i>
                {% else %}
                <i class="fa-solid fa-file-lines text-secondary"></i>
                {% endif %}
                {% endif %}
            </div>

            <!-- 文件信息部分 -->
            <div class="flex-grow-1 ms-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        {% if item.file_type == 2 %}
                        <!-- 文件夹链接 -->
                        <a href="?folder_id={{ item.id }}" class="text-decoration-none text-dark">
                            <h6 class="mb-0">{{ item.name }}</h6>
                        </a>
                        <small class="text-muted">文件夹</small>
                        {% else %}
                        <h6 class="mb-0">{{ item.name }}</h6>
                        <small class="text-muted">
                            {{ item.get_file_type_display }} ·
                            {{ item.file_size|filesizeformat }}
                        </small>
                        {% endif %}
                    </div>

                    <div class="text-end">
                        <small class="text-muted me-3" style="position: relative; top: 12px">
                            文件大小：{{ item.file_size|filesizeformat }}
                        </small>
                        <small class="text-muted">
                            最后更新：{{ item.update_datetime|date:"Y-m-d H:i" }}
                        </small>
                        <div class="text-muted small">
                            更新者：{{ item.update_user.usermail }}
                        </div>
                    </div>
                </div>
            </div>

            <!-- 操作按钮 -->
            <div class="ms-3 d-flex justify-content-end align-items-center">
                {% if item.file_type == 1 %}
                <!-- 下载按钮 -->
                <a href="{{ item.file_path }}" class="btn btn-link text-decoration-none" download>
                    <i class="fa-solid fa-download"></i>
                </a>
                {% endif %}

                {% if item.file_type == 2 %}
                <!-- 编辑按钮 -->
                <button data-bs-toggle="modal" data-bs-target="#addModal" data-whatever="编辑文件夹"
                    data-name="{{item.name}}" data-fid="{{item.id}}" type="button" class="btn btn-primary btn-sm"
                    style="font-size: 12px;">
                    <i class="fa-solid fa-pencil"></i>
                    编辑
                </button>
                {% endif %}

                <!-- 分隔线 -->
                <div class="vr mx-2"></div>

                <!-- 删除按钮 -->
                <button data-bs-toggle="modal" data-bs-target="#alertModal" data-fid="{{item.id}}" type="button"
                    class="btn btn-danger btn-sm" style="font-size: 12px;">
                    <i class="fa-solid fa-trash-can"></i>
                    删除
                </button>
            </div>
        </div>
        {% endfor %}
    </div>

</div>

<!-- 模态对话框 -->
<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- 头部 -->
            <div class="modal-header">
                <h5 class="modal-title">对话框标题</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <!-- 内容 -->
            <div class="modal-body">
                <form id="form">
                    {% csrf_token %}
                    {% for field in form %}
                    <input class="d-none" type="text" name="fid" id="fid" value="">
                    <div class="mb-3">
                        <label for="{{field.id_for_label}}" class="col-form-label">{{field.label}}</label>
                        {{ field }}
                        <div class="text-danger" style="margin-left: 4px;position: absolute;font-size: 14px;">
                            {{ field.errors.0 }}
                        </div>
                    </div>
                    {% endfor %}
                </form>
            </div>
            <!-- 底部 -->
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button id="btnFormSubmit" type="button" class="btn btn-primary">保存</button>
            </div>
        </div>
    </div>
</div>
<div class="modal" tabindex="-1" role="dialog" id="alertModal">
    <div class="modal-dialog">
        <div class="modal-content rounded-4 shadow">
            <div class="modal-header border-bottom-0">
                <h1 class="modal-title fs-5">是否确认删除文件夹？</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body py-0">
                <p><span style="color: red; font-size: 20px;">注意！</span>——文件夹所有文件都会被删除，删除后无法恢复文件，请谨慎操作~</p>
            </div>
            <div class="modal-footer flex-column align-items-stretch w-100 gap-2 pb-3 border-top-0">
                <button id="btnDelete" type="button" class="btn btn-lg btn-danger">确认删除</button>
                <button type="button" class="btn btn-lg btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<div id="uploadProgress" class="upload-progress d-none">
    <div class="card border-primary">
        <div class="card-header bg-primary text-white d-flex justify-content-between" style="padding: 3px;">
            <span><i class="bi bi-cloud-upload"></i> 上传进度</span>
            <button id="closeUploadProgress" class="btn btn-sm btn-light">×</button>
        </div>
        <div class="card-body">
            <table class="table" id="progressList"></table>
        </div>
    </div>
</div>


<div class="d-none">
    <table id="progressTemplate">
        <!-- 默认进度条 -->
        <tr>
            <td>
                <div class="name" style="font-size: 12px;">photo.jpg</div>
                <div class="position-relative rounded" style="height: 30px;">
                    <!-- 原有进度条 -->
                    <div class="progress position-absolute top-0 start-0"
                        style="height: 30px; width: 100%; border-radius: 15px;">
                        <div class="progress-bar progress-bar-striped bg-success" role="progressbar"
                            style="width: 100%; border-radius: 15px;" aria-valuenow="0" aria-valuemin="0"
                            aria-valuemax="100">
                            0%
                        </div>
                    </div>
                </div>
                <div class="progress-error"></div>
            </td>
        </tr>
    </table>
</div>
<div class="d-none">
    <table id="rowTpl">
        <tr>
            <td>
                <i class="fa fa-file" aria-hidden="true"></i>
                <span class="name"></span>
            </td>
            <td class="file_size"></td>
            <td class="usermail"></td>
            <td class="datetime"></td>
            <td>

                <a class="btn btn-default btn-xs download">
                    <i class="fa fa-cloud-download" aria-hidden="true"></i>
                </a>

                <a class="btn btn-danger btn-xs delete" data-toggle="modal" data-target="#alertModal">
                    <i class="fa fa-trash" aria-hidden="true"></i>
                </a>
            </td>
        </tr>
    </table>
</div>
{% endblock %}

{% block js1 %}
<script src="{% static 'JS/cos-js-sdk-v5.min.js' %}"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    /* 文件上传出错弹出框 */
    // 全局错误处理函数
    function showErrorModal(errorMsg) {
        Swal.fire({
            title: '<i class="swal2-icon swal2-error swal2-animate-error-icon" style="display: flex;"></i>',
            html: `<div style="padding: 0 1.5rem;">
            <div style="color: #666; line-height: 1.6;">${errorMsg}</div>
            <div style="margin-top: 1rem; color: #999; font-size: 0.9em;">
              需要帮助？<a href="/pricing" style="color: #1890ff;">查看升级方案</a>
            </div>
          </div>`,
            showConfirmButton: true,
            confirmButtonText: '我知道了',
            showCloseButton: true,
            customClass: {
                container: 'swal2-container-custom',
                popup: 'swal2-popup-custom'
            },
            background: '#fff',
            width: 480,
            padding: '2rem'
        });
    }
</script>

<script>
    let FOLDER_URL = "{% url 'file' project_id=request.tracer.project.id %}"
    let FILE_DELETE_URL = "{% url 'file_delete' project_id=request.tracer.project.id %}"
    let FILE_UPLOAD_URL = "{% url 'cos_credentials' project_id=request.tracer.project.id %}"
    let FILE_POST_URL = "{% url 'file_post' project_id=request.tracer.project.id %}"
    let CURRENT_FOLDER_ID = "{{ folder_object.id }}"

    $(function () {
        initAddModal();
        bindModelSubmit();
        bindDeleteSubmit();
        bindUploadSubmit();
    })

    // 手动关闭按钮事件
    $('#closeUploadProgress').click(function () {
        $('#uploadProgress').addClass('d-none');
    });

    function bindUploadSubmit() {
        $("#uploadFile").change(function () {
            $("#uploadProgress").addClass('d-none');
            $("#progressList").empty();

            var file_list = $(this)[0].files;
            let checkFileList = [];

            $.each(file_list, function (index, fileObject) {
                checkFileList.push({ "name": fileObject.name, "size": fileObject.size });
            });

            let cos_credential = new COS({
                getAuthorization: function (options, callback) {
                    $.post(FILE_UPLOAD_URL, JSON.stringify(checkFileList), function (res) {
                        if (res.status) {
                            let credentials = res.data && res.data.credentials;
                            if (!res.data || !credentials) return console.error('credentials invalid');
                            callback({
                                TmpSecretId: credentials.tmpSecretId,
                                TmpSecretKey: credentials.tmpSecretKey,
                                XCosSecurityToken: credentials.sessionToken,
                                StartTime: res.data.startTime,
                                ExpiredTime: res.data.expiredTime,
                            });
                            $('#uploadProgress').removeClass('d-none');
                        } else {
                            showErrorModal(res.error);
                        }
                    });
                }
            });

            $.each(file_list, function (index, fileObject) {
                let $tr = $("#progressTemplate").find('tr').clone();
                $tr.find('.name').text('上传文件：' + fileObject.name);
                $('#progressList').append($tr);

                let fileName = fileObject.name;
                let fileSize = fileObject.size;
                let key = (new Date()).getTime() + '-' + fileName;

                cos_credential.putObject({
                    Bucket: '{{ request.tracer.project.bucket }}',
                    Region: '{{ request.tracer.project.region }}',
                    Key: key,
                    Body: fileObject,
                    onProgress: function (progressData) {
                        var percent = progressData.percent * 100 + '%';
                        $tr.find('.progress-bar').text(percent);
                        $tr.find('.progress-bar').css('width', percent);
                    }
                }, function (err, data) {
                    console.log(err || data);

                    if (data && data.statusCode === 200) {
                        // COS上传成功, 向后端提交文件信息写入数据库
                        $.post(FILE_POST_URL, {
                            name: fileName,
                            key: key,
                            file_size: fileSize,
                            parent: CURRENT_FOLDER_ID,
                            etag: data.ETag,
                            file_path: data.Location
                        }, function (res) {
                            console.log(res);
                            if (res.status) {
                                // 数据库写入成功，更新UI
                                var newTr = $('#rowTpl').find('tr').clone();
                                newTr.find('.delete').attr('data-fid', res.data.id);
                                newTr.find('.name').text(res.data.name);
                                newTr.find('.file_size').text(res.data.file_size);
                                newTr.find('.usermail').text(res.data.usermail);
                                newTr.find('.datetime').text(res.data.datetime);
                                $('#rowList').append(newTr);
                                $tr.remove();  // 删除进度条
                                location.reload();
                            } else {
                                // 如果数据库写入失败
                                $tr.find('.progress-error').text('写入数据库失败：' + res.error.name[0]);
                            }
                        }).fail(function (error) {
                            // 处理服务器错误
                            $tr.find('.progress-error').text('请求后端失败：' + error.statusText);
                        });
                    } else {
                        // COS上传失败
                        $tr.find('.progress-error').text('上传到COS失败');
                    }
                });
            });
        });
    }

    function bindDeleteSubmit() {
        $("#btnDelete").click(function () {
            // 获取删除行的ID
            $.ajax({
                url: FILE_DELETE_URL,
                type: 'GET',
                data: { fid: $(this).attr('fid') },
                dataType: 'JSON',
                success: function (res) {
                    if (res.status) {
                        location.reload()
                    }
                }
            })
        })

    }
    function initAddModal() {
        $('#addModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget)
            var recipient = button.data('whatever')
            var name = button.data('name')
            var fid = button.data('fid')
            var modal = $(this)
            modal.find('.modal-title').text(recipient)
            if (fid) {
                // 编辑 - 保留文件名
                $('#id_name').val(name)
                $('#fid').val(fid)
            }
            else {
                // 新建
                // 点击清空错误信息
                modal.find('.text-danger').empty()
                // 点击清空输入对象
                $('#form')[0].reset()
            }
        })

        $('#alertModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget)
            var fid = button.data('fid')
            var modal = $(this)
            $("#btnDelete").attr('fid', fid)
        })
    }

    function bindModelSubmit() {
        $('#btnFormSubmit').click(function () {
            $.ajax({
                url: location.href,
                type: 'POST',
                data: $('#form').serialize(),
                dataType: 'JSON',
                success: function (res) {
                    if (res.status) {
                        location.reload()
                    }
                    else {
                        $.each(res.error, function (key, value) {
                            $("#id_" + key).next().text(value[0])
                        })
                    }
                }
            })
        })
    }
</script>
{% endblock %}